<?php

namespace App\Http\Controllers;

class JustwenCode extends Controller
{

    //获取验证码
    public static function getCode(array $payload)
    {
        // 配置签名信息
        $arr = [
            'iat' => time(), //签发时间
            'exp' => time() + 60, //过期时间（1分钟）

        ];
        $payload = array_merge($arr, $payload);
        if (is_array($payload)) {
            $base64header = 'justwen';
            $base64payload = self::base64UrlEncode(json_encode($payload, JSON_UNESCAPED_UNICODE));
            $token = $base64header . '.' . $base64payload;
            return $token;
        } else {
            return false;
        }
    }
    //校验验证码
    public static function verifyCode(string $Token)
    {
        $tokens = explode('.', $Token);

        list($name, $base64payload) = $tokens;
        // //签发时间大于当前服务器时间验证失败
        if ($name != 'justwen') {
            return false;
        }

        $payload = json_decode(self::base64UrlDecode($base64payload), JSON_OBJECT_AS_ARRAY);

        // //签发时间大于当前服务器时间验证失败
        if (isset($payload['iat']) && $payload['iat'] > time()) {
            return false;
        }

        //过期时间小宇当前服务器时间验证失败
        if (isset($payload['exp']) && $payload['exp'] < time()) {
            return false;
        }

        //该nbf时间之前不接收处理该Token
        if (isset($payload['nbf']) && $payload['nbf'] > time()) {
            return false;
        }

        return $payload['code'];
    }

    private static function base64UrlEncode(string $input)
    {
        return str_replace('=', '', strtr(base64_encode($input), '+/', '-_'));
    }

    private static function base64UrlDecode(string $input)
    {
        $remainder = strlen($input) % 4;
        if ($remainder) {
            $addlen = 4 - $remainder;
            $input .= str_repeat('=', $addlen);
        }
        return base64_decode(strtr($input, '-_', '+/'));
    }

}
